# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.url_manageDao import UrlManageDao
from com.zzh.dao_v2.AuthTokenOperation import authTokenOperation
import time
from . import app

localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


CORS(app, supports_credentials=True)




# ----------------------------------------url_manage    url管理表-------------------------------------


@app.route('/addUrlManage', methods=['POST'])
def addUrlManage():
    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')
    except Exception, e :
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:
        localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        url_manage_info = {

            "level_code": request.json.get('levelCode'),
            "dept_name": request.json.get('deptName'),
            "dept_url": request.json.get('deptUrl'),
            "des_url": request.json.get('desUrl'),
            "evidence_url": request.json.get('evidenceUrl'),

            "face_keywords": request.json.get('faceKeywords'),
            "opposite_keywords": request.json.get('oppositeKeywords'),
            "check_status": request.json.get('checkStatus'),
            "balance_status": request.json.get('balanceStatus'),

            "check_time": request.json.get('checkTime'),

            "province_id": request.json.get('provinceId'),
            "city_id": request.json.get('cityId'),
            "district_id": request.json.get('districtId'),

            "enter_person": request.json.get('enterPerson'),
            "enter_time": localTime,
            "check_remark": request.json.get('checkRemark'),
            "check_person": request.json.get('checkPerson'),
            "dept_status": request.json.get('deptStatus')
        }
        try:
            rs = UrlManageDao().add_url_manage(url_manage_info)
            if rs:
                return jsonify({"message": {"code": 1, "info": "添加成功！"}})
            else:

                return jsonify({"message": {"code": 0, "info": "添加失败！"}})
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})

    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/delUrlManage', methods=['POST'])
def delUrlManage():

    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')

    except:
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:

        #这个地方添加实际的业务代码，每个api的原来的代码移动到这里面
        #同时把下方return jsonify({"message":"Token验证成功"})去掉

        ids = request.json.get('ids')
        try:
            res = UrlManageDao().del_url_manage(ids)
            if res:
                return jsonify({"message": {"code": 1, "info": " delete OK"}})
            else :
                return jsonify({"message":{"code":0,"info":"No records"}})
        except Exception:
            return jsonify({"code":0,"message":str(Exception)})


    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/generateToken"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/queryUrlManageById', methods=['POST'])
def queryUrlManageById():

    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')

    except:
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:
        url_manage_id = request.json.get('id')
        try:
            result, totalCount = UrlManageDao().query_url_manage(url_manage_id)
            if totalCount:
                return jsonify({"info": result, "message": "查询成功！"})
            else:

                return jsonify({"info": [], "message": {"code": 1, "status": "error"}})
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/updateUrlManageCheckStatus',methods=['POST'])
def updateUrlManageCheckStatus():
    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:
        ids = request.json.get('ids')
        checkStatus = request.json.get('checkStatus')
        checkPerson = request.json.get('checkPerson')
        checkRemark = request.json.get('checkRemark')
        try:
            rs = UrlManageDao().updateUrlManageCheckStatus(checkStatus, ids, checkPerson, checkRemark)
            if rs:
                return jsonify({"message": {"code": 1, "info": "updateCheckStatus OK"}})
            else:
                return jsonify({"message": {"code": 0, "info": "updateCheckStatus Failed,请检查id是否存在"}})
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/updateUrlManage', methods=['POST'])
def updateUrlManage():

    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:
        try:
            url_manage_id = request.json.get('id')
        except Exception,e:
            return jsonify({"message": {"code": 0, "status": "请传入 id"}})
        try:
            oldInfo = UrlManageDao().selectUrlManage(url_manage_id)
            if oldInfo == None:
                return jsonify({"message": {"code": 0, "info": "请检查id值是否正确"}})
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
        new_url_manage = {
            "level_code": request.json.get('levelCode', oldInfo[1]),
            "dept_name": request.json.get('deptName', oldInfo[2]),
            "dept_url": request.json.get('deptUrl', oldInfo[3]),
            "des_url": request.json.get('desUrl', oldInfo[4]),
            "evidence_url": request.json.get('evidence_url', oldInfo[5]),

            "face_keywords": request.json.get('faceKeywords', oldInfo[6]),
            "opposite_keywords": request.json.get('oppositeKeywords', oldInfo[7]),
            "check_status": request.json.get('checkStatus', oldInfo[8]),
            "balance_status": request.json.get('balanceStatus', oldInfo[9]),

            "check_time": request.json.get('checkTime', oldInfo[10]),

            "province_id": request.json.get('provinceId', oldInfo[11]),
            "city_id": request.json.get('cityId', oldInfo[12]),
            "district_id": request.json.get('districtId', oldInfo[13]),

            "enter_person": request.json.get('enterPerson', oldInfo[14]),
            "enter_time": request.json.get('enterTime', oldInfo[15]),
            "check_remark": request.json.get('checkRemark', oldInfo[16]),
            "check_person": request.json.get('checkPerson', oldInfo[17]),
            "dept_status": request.json.get('deptStatus', oldInfo[18])
        }
        if not new_url_manage:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            updateresult = UrlManageDao().update_url_manage(new_url_manage, url_manage_id)
            if updateresult:
                return jsonify({"info": updateresult,
                                "message": {"code": 1, "info": "update OK"}})
            else:
                return jsonify({"message": {"code": 0, "info": "update Failed"}})
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/queryUrlManageByCondition', methods=['POST'])
def queryUrlManageByCondition():
    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数token"}})
    try:
        checkResult = authTokenOperation().veryfyToken(token)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    if checkResult:
        try:
            page = request.json['page']
            pageIndex = page["pageIndex"]
            pageSize = page["pageSize"]
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})
        try:
            conditions = request.json['condition']
        except:
            return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
        try:
            multiSort = request.json['multiSort']
        except:
            return jsonify({"message": "未传入排序规则multiSort"})
        try:
            UrlManageJSON, total_count = UrlManageDao().queryUrlManageByCondition(pageIndex=pageIndex, pageSize=pageSize,
                                                                                  conditions=conditions,
                                                                                  multiSort=multiSort)

            if total_count:
                return jsonify(
                    {"message": {"code": 1, "status": "queryUrlManage OK"}, "total": total_count, "info": UrlManageJSON})
            else:
                return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
        except Exception, e:
                return jsonify({"message": {"code": 0, "info": str(e)}})
    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"messge": "token验证失败，请重新前往以下链接验证用户名和密码", "userLoginUrl": loginUrl})



